<template>
    <div class="leave-school-manage">
        <el-tabs v-model="activeTab" @tab-click="onTabClick">
            <el-tab-pane label="今日考勤" name="today" />
            <el-tab-pane label="缺勤统计" name="absence" />
            <el-tab-pane label="历史考勤" name="history" />
            <el-tab-pane label="请假管理" name="leave" />
            <el-tab-pane label="离校管理" name="leaveSchool" />
            <el-tab-pane label="考勤时间设置" name="setting" />
        </el-tabs>
        <div class="filter-bar">
            <el-date-picker v-model="date" type="date" placeholder="选择日期" style="width: 150px; margin-right: 10px;" />
            <el-select v-model="leaveSchoolStatus" placeholder="离校状态" style="width: 130px; margin-right: 10px;">
                <el-option label="全部" value="" />
                <el-option label="已确认离校" value="已确认离校" />
                <el-option label="未确认离校" value="未确认离校" />
            </el-select>
            <el-select v-model="className" placeholder="班级" style="width: 150px; margin-right: 10px;">
                <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <el-input v-model="studentName" placeholder="学生姓名" style="width: 130px; margin-right: 10px;" />
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
            <el-button type="success" @click="showAddLeaveSchoolDialog" style="margin-left: 8px;">添加离校</el-button>
            <el-button type="info" @click="handleRefresh" style="margin-left: 8px;">
                <el-icon>
                    <Refresh />
                </el-icon> 刷新数据
            </el-button>
        </div>
        <div class="result-info">查询结果：共计 {{ totalItems }} 条数据</div>
        <el-table :data="tableData" border style="width: 100%; margin-top: 10px;" v-loading="loading">
            <el-table-column prop="className" label="班级" width="140" />
            <el-table-column prop="studentName" label="学生姓名" width="100" />
            <el-table-column prop="leaveTime" label="离校时间" width="150" />
            <el-table-column prop="returnTime" label="预计返校时间" width="150" />
            <el-table-column prop="reason" label="离校原因" width="100" />
            <el-table-column prop="escort" label="接送人" width="80" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="210">
                <template #default="scope">
                    <el-button v-if="scope.row.status === '待审批'" type="success" size="small"
                        @click="approveLeaveSchool(scope.row)">
                        批准
                    </el-button>
                    <el-button v-if="scope.row.status === '待审批'" type="danger" size="small"
                        @click="rejectLeaveSchool(scope.row)">
                        拒绝
                    </el-button>
                    <el-button v-if="scope.row.status === '已离校'" type="primary" size="small"
                        @click="confirmReturn(scope.row)">
                        确认返校
                    </el-button>
                    <el-button type="info" size="small" @click="viewDetail(scope.row)">
                        详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
                layout="total, sizes, prev, pager, next, jumper" :total="totalItems" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="离校详情" width="30%">
            <div>
                <p><strong>学生：</strong>{{ currentLeave.studentName }}</p>
                <p><strong>学号：</strong>{{ currentLeave.studentId }}</p>
                <p><strong>班级：</strong>{{ currentLeave.className }}</p>
                <p><strong>离校时间：</strong>{{ currentLeave.leaveTime }}</p>
                <p><strong>预计返校时间：</strong>{{ currentLeave.returnTime }}</p>
                <p><strong>离校原因：</strong>{{ currentLeave.reason }}</p>
                <p><strong>接送人：</strong>{{ currentLeave.escort }}</p>
                <p><strong>状态：</strong>{{ currentLeave.status }}</p>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 添加离校对话框 -->
        <el-dialog v-model="addLeaveSchoolDialogVisible" title="添加离校申请" width="40%">
            <el-form :model="leaveSchoolForm" label-width="100px" :rules="rules" ref="leaveSchoolFormRef">
                <el-form-item label="学生姓名" prop="studentName">
                    <el-input v-model="leaveSchoolForm.studentName" placeholder="请输入学生姓名" />
                </el-form-item>
                <el-form-item label="学号" prop="studentId">
                    <el-input v-model="leaveSchoolForm.studentId" placeholder="请输入学号" />
                </el-form-item>
                <el-form-item label="班级" prop="className">
                    <el-select v-model="leaveSchoolForm.className" placeholder="请选择班级" style="width: 100%;">
                        <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="离校时间" prop="leaveTime">
                    <el-date-picker v-model="leaveSchoolForm.leaveTime" type="datetime" placeholder="选择离校时间"
                        style="width: 100%;" />
                </el-form-item>
                <el-form-item label="预计返校时间" prop="returnTime">
                    <el-date-picker v-model="leaveSchoolForm.returnTime" type="datetime" placeholder="选择预计返校时间"
                        style="width: 100%;" />
                </el-form-item>
                <el-form-item label="离校原因" prop="reason">
                    <el-input v-model="leaveSchoolForm.reason" type="textarea" rows="3" placeholder="请输入离校原因" />
                </el-form-item>
                <el-form-item label="接送人" prop="escort">
                    <el-input v-model="leaveSchoolForm.escort" placeholder="请输入接送人姓名" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addLeaveSchoolDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitLeaveSchoolForm" :loading="submitting">提交</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getClassList, getLeaveSchoolList, approveLeaveSchool as apiApproveLeaveSchool, resetCache, addLeaveSchoolRecord } from '../../api/kaoqin'
import type { ClassItem, LeaveSchoolItem } from '../../api/kaoqin.d.ts'

const router = useRouter()
const route = useRoute()
const activeTab = ref('leaveSchool')
const loading = ref(false)
const submitting = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const allLeaveSchoolData = ref<LeaveSchoolItem[]>([])
const totalItems = computed(() => allLeaveSchoolData.value.length)

// 监听路由变化高亮对应tab
watch(
    () => route.path,
    (path) => {
        if (path.includes('/main/attendance/manage')) {
            activeTab.value = 'today'
        } else if (path.includes('/main/attendance/absence')) {
            activeTab.value = 'absence'
        } else if (path.includes('/main/attendance/history')) {
            activeTab.value = 'history'
        } else if (path.includes('/main/attendance/leave')) {
            activeTab.value = 'leave'
        } else if (path.includes('/main/attendance/leaveSchool')) {
            activeTab.value = 'leaveSchool'
        } else if (path.includes('/main/attendance/setting')) {
            activeTab.value = 'setting'
        }
    },
    { immediate: true }
)

// 标签页切换
function onTabClick(tab: any) {
    if (tab.paneName === 'today') {
        router.push('/main/attendance/manage')
    } else if (tab.paneName === 'absence') {
        router.push('/main/attendance/absence')
    } else if (tab.paneName === 'history') {
        router.push('/main/attendance/history')
    } else if (tab.paneName === 'leave') {
        router.push('/main/attendance/leave')
    } else if (tab.paneName === 'leaveSchool') {
        router.push('/main/attendance/leaveSchool')
    } else if (tab.paneName === 'setting') {
        router.push('/main/attendance/setting')
    }
}

const date = ref('2025-03-15')
const leaveSchoolStatus = ref('')
const className = ref('')
const studentName = ref('')
const classOptions = ref<string[]>([])
const tableData = ref<LeaveSchoolItem[]>([])

const detailDialogVisible = ref(false)
const currentLeave = ref<LeaveSchoolItem>({} as LeaveSchoolItem)

// 添加离校相关
const addLeaveSchoolDialogVisible = ref(false)
const leaveSchoolFormRef = ref<FormInstance>()
const leaveSchoolForm = reactive({
    studentName: '',
    studentId: '',
    className: '',
    leaveTime: '',
    returnTime: '',
    reason: '',
    escort: '',
})

const rules = {
    studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
    studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
    className: [{ required: true, message: '请选择班级', trigger: 'change' }],
    leaveTime: [{
        required: true,
        message: '请选择离校时间',
        trigger: 'change',
        validator: (rule: any, value: any, callback: any) => {
            if (!value) {
                callback(new Error('请选择离校时间'));
            } else {
                callback();
            }
        }
    }],
    returnTime: [{
        required: true,
        message: '请选择预计返校时间',
        trigger: 'change',
        validator: (rule: any, value: any, callback: any) => {
            if (!value) {
                callback(new Error('请选择预计返校时间'));
            } else if (leaveSchoolForm.leaveTime && new Date(value) <= new Date(leaveSchoolForm.leaveTime)) {
                callback(new Error('返校时间必须晚于离校时间'));
            } else {
                callback();
            }
        }
    }],
    reason: [{ required: true, message: '请输入离校原因', trigger: 'blur' }],
    escort: [{ required: true, message: '请输入接送人姓名', trigger: 'blur' }]
}

// 获取班级列表
async function fetchClassList() {
    try {
        const response = await getClassList()
        if (response.data && response.data.code === 200) {
            classOptions.value = response.data.data.map((item: ClassItem) => item.className)
        } else {
            // 回退到静态数据
            classOptions.value = ['一年级（1）班', '一年级（2）班']
        }
    } catch (error) {
        console.error('获取班级列表失败:', error)
        // 回退到静态数据
        classOptions.value = ['一年级（1）班', '一年级（2）班']
    }
}

// 获取离校列表
async function fetchLeaveSchoolList() {
    loading.value = true
    try {
        const params = {
            date: date.value,
            status: leaveSchoolStatus.value,
            className: className.value,
            studentName: studentName.value
        }

        const response = await getLeaveSchoolList(params)
        if (response.data && response.data.code === 200) {
            // 保存所有数据用于分页
            allLeaveSchoolData.value = response.data.data
            updatePagedData()
        } else {
            ElMessage.error('获取离校列表失败')
        }
    } catch (error) {
        console.error('获取离校列表失败:', error)
        ElMessage.error('获取离校列表失败')
    } finally {
        loading.value = false
    }
}

// 更新分页数据
function updatePagedData() {
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    tableData.value = allLeaveSchoolData.value.slice(startIndex, endIndex)
}

// 处理分页大小变化
function handleSizeChange(size: number) {
    pageSize.value = size
    updatePagedData()
}

// 处理当前页变化
function handleCurrentChange(page: number) {
    currentPage.value = page
    updatePagedData()
}

// 查询按钮
function handleQuery() {
    currentPage.value = 1
    fetchLeaveSchoolList()
}

// 重置按钮
function handleReset() {
    date.value = '2025-03-15'
    leaveSchoolStatus.value = ''
    className.value = ''
    studentName.value = ''
    currentPage.value = 1
    fetchLeaveSchoolList()
}

// 刷新数据按钮
async function handleRefresh() {
    loading.value = true
    try {
        // 重置API缓存，生成新的随机数据
        resetCache()

        ElMessage({
            message: '正在刷新数据...',
            type: 'info'
        })

        // 重新获取班级和离校数据
        await fetchClassList()
        await fetchLeaveSchoolList()

        ElMessage({
            message: '数据刷新成功！',
            type: 'success'
        })
    } catch (error) {
        console.error('刷新数据失败:', error)
        ElMessage.error('刷新数据失败')
    } finally {
        loading.value = false
    }
}

// 查看离校详情
function viewDetail(row: LeaveSchoolItem) {
    currentLeave.value = row
    detailDialogVisible.value = true
}

// 显示添加离校对话框
function showAddLeaveSchoolDialog() {
    console.log('打开添加离校对话框');
    console.log('当前班级选项:', classOptions.value);

    addLeaveSchoolDialogVisible.value = true;

    // 重置表单
    Object.assign(leaveSchoolForm, {
        studentName: '',
        studentId: '',
        className: classOptions.value[0] || '',
        leaveTime: new Date(), // 设置默认值为当前时间
        returnTime: new Date(new Date().getTime() + 2 * 60 * 60 * 1000), // 默认返校时间为当前时间加2小时
        reason: '',
        escort: ''
    });

    console.log('初始化后的表单数据:', leaveSchoolForm);

    // 如果表单引用存在，重置验证信息
    if (leaveSchoolFormRef.value) {
        leaveSchoolFormRef.value.resetFields();
    }
}

// 提交离校表单
async function submitLeaveSchoolForm() {
    if (!leaveSchoolFormRef.value) return

    await leaveSchoolFormRef.value.validate(async (valid) => {
        if (valid) {
            submitting.value = true
            try {
                console.log('表单数据:', leaveSchoolForm); // 调试信息

                // 格式化日期时间
                const leaveTime = formatDateTime(leaveSchoolForm.leaveTime);
                const returnTime = formatDateTime(leaveSchoolForm.returnTime);

                console.log('格式化后的时间:', { leaveTime, returnTime }); // 调试信息

                // 创建新的离校数据
                const leaveSchoolData = {
                    studentName: leaveSchoolForm.studentName,
                    studentId: leaveSchoolForm.studentId,
                    className: leaveSchoolForm.className,
                    leaveTime,
                    returnTime,
                    reason: leaveSchoolForm.reason,
                    escort: leaveSchoolForm.escort,
                    status: '待审批'
                };

                // 调用API添加离校记录
                console.log('准备提交数据:', leaveSchoolData); // 调试信息
                const response = await addLeaveSchoolRecord(leaveSchoolData);
                console.log('API响应:', response); // 调试信息

                if (response.data && response.data.code === 200) {
                    ElMessage.success('离校申请提交成功');
                    addLeaveSchoolDialogVisible.value = false;

                    // 重新加载数据并设置当前页为第一页
                    currentPage.value = 1;
                    await fetchLeaveSchoolList();

                    // 确保新记录显示在顶部
                    if (allLeaveSchoolData.value.length > 0) {
                        // 手动更新分页数据以确保即时显示
                        updatePagedData();
                    }
                } else {
                    ElMessage.error(response.data?.message || '提交失败');
                }
            } catch (error) {
                console.error('提交离校申请失败详情:', error);
                ElMessage.error('提交离校申请失败');
            } finally {
                submitting.value = false;
            }
        } else {
            console.log('表单验证失败'); // 调试信息
        }
    })
}

// 日期时间格式化工具函数
function formatDateTime(dateTime: any) {
    if (!dateTime) return '';

    try {
        // 如果已经是格式化的字符串，直接返回
        if (typeof dateTime === 'string') {
            // 检查是否已经是 YYYY-MM-DD HH:MM 格式
            if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(dateTime)) {
                return dateTime;
            }
            // 尝试将字符串转换为日期对象
            dateTime = new Date(dateTime);
        }

        // 处理日期对象
        if (dateTime instanceof Date) {
            const year = dateTime.getFullYear();
            const month = String(dateTime.getMonth() + 1).padStart(2, '0');
            const day = String(dateTime.getDate()).padStart(2, '0');
            const hours = String(dateTime.getHours()).padStart(2, '0');
            const minutes = String(dateTime.getMinutes()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }

        console.error('无法格式化日期:', dateTime);
        return '';
    } catch (error) {
        console.error('日期格式化错误:', error);
        return '';
    }
}

// 批准离校
async function approveLeaveSchool(row: LeaveSchoolItem) {
    try {
        const data = {
            status: '已离校'
        }

        const response = await apiApproveLeaveSchool(row.id, data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('已批准该离校申请')
            fetchLeaveSchoolList() // 刷新列表
        } else {
            ElMessage.error('操作失败')
        }
    } catch (error) {
        console.error('批准离校失败:', error)
        ElMessage.error('批准离校失败')
    }
}

// 拒绝离校
async function rejectLeaveSchool(row: LeaveSchoolItem) {
    try {
        const data = {
            status: '已拒绝'
        }

        const response = await apiApproveLeaveSchool(row.id, data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('已拒绝该离校申请')
            fetchLeaveSchoolList() // 刷新列表
        } else {
            ElMessage.error('操作失败')
        }
    } catch (error) {
        console.error('拒绝离校失败:', error)
        ElMessage.error('拒绝离校失败')
    }
}

// 确认返校
async function confirmReturn(row: LeaveSchoolItem) {
    try {
        const data = {
            status: '已返校'
        }

        const response = await apiApproveLeaveSchool(row.id, data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('已确认返校')
            fetchLeaveSchoolList() // 刷新列表
        } else {
            ElMessage.error('操作失败')
        }
    } catch (error) {
        console.error('确认返校失败:', error)
        ElMessage.error('确认返校失败')
    }
}

// 根据状态获取标签类型
function getStatusTagType(status: string) {
    switch (status) {
        case '待审批':
            return 'warning'
        case '已离校':
            return 'danger'
        case '已返校':
            return 'success'
        case '已拒绝':
            return 'info'
        default:
            return ''
    }
}

// 组件挂载时强制设置正确的标签页
onMounted(() => {
    // 确保离校管理页面的标签页正确显示
    if (route.path.includes('/main/attendance/leaveSchool')) {
        activeTab.value = 'leaveSchool'
    }
    fetchClassList()
    fetchLeaveSchoolList()
})
</script>

<style scoped>
.leave-school-manage {
    background: #f7fafd;
    padding: 20px;
}

.filter-bar {
    margin: 20px 0 10px 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.result-info {
    margin-bottom: 10px;
    color: #409eff;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style>